﻿var serverDirs = function () {
    function init() {
        if ($('body').find('div.modal').length == 0) {
            var sr = $('<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">' +
                            '<div class="modal-dialog modal-sm" role="document">' +
                                 '<div class="modal-content">' +
                                '</div>' +
                            '</div>' +
                        '</div>');
            $('body').append(sr);
        }
    }

    function openDir(path, obj) {
        $.get('/api/serverDirs/getDirs', { vpath: path }, function (data) {
            var div = $('<div></div>');
            div.addClass('list-group');
            var ls = data.dirs;
            for (var i = 0; i < ls.length; i++) {
                var p = ls[i];
                var aa = $('<a></a>');
                aa.addClass('list-group-item');
                aa.attr('href', '#');
                if (p.isdir) {
                    aa.append($('<span class="glyphicon glyphicon-folder-close" aria-hidden="true"></span>'));
                    aa.attr('onclick', 'serverDirs.openDir(\'' + p.path + p.name + '\',this);');
                } else {
                    aa.append($('<span class="glyphicon glyphicon-file" aria-hidden="true"></span>'));
                    aa.attr('onclick', 'serverDirs.openFile(\'' + p.path + p.name + '\');');
                }
                aa.append('  ' + p.name);
                div.append(aa);
            }
            if (ls.length > 0) {
                $(obj).append(div);
            }
            $(obj).removeAttr('onclick');
            $(obj).children('span.glyphicon-folder-close')
                .removeClass('glyphicon-folder-close')
                .addClass('glyphicon-folder-open');
        });
    }

    function openFile(path) {
        if (serverDirs.callback != null) {
            serverDirs.callback(path);
        }
    }

    return {
        init: init,
        openDir: openDir,
        openFile: openFile,
        callback: null,
        click: function (name) {
            serverDirs.init();
            var div = $('div.modal-content');
            serverDirs.openDir(null, div);
            serverDirs.callback = function (str) {
                $('div.modal').modal('hide')
                $('input[name="' + name + '"]').val(str);
                div.html('');
            }
            $('div.modal').modal('show');
        }
    }
}();